<?php

namespace App\Service\Content;

use App\Constants\Redis\TempRedisCode;
use App\Model\Content\AdGroupModel;
use App\Model\Content\AdModel;
use App\Service\BaseService;
use Hyperf\Di\Annotation\Inject;

class AdService extends BaseService
{

    #[Inject]
    protected AdGroupModel $adGroupModel;

    #[Inject]
    protected AdModel $adModel;

    public function adGroupPageList($params=[], $page=1, $ps=15)
    {
        return $this->adGroupModel->pageListForAdmin($params, $page, $ps);
    }

    public function addAdGroup($params)
    {
        $codeEx = $this->adGroupModel->findByCode($params['code'],['id']);
        if ($codeEx){
            return [false,'唯一标识已经存在'];
        }
        $r = $this->adGroupModel->addOne($params);
        if ($r){
            return [true,'添加成功'];
        }
        return [false,'添加失败'];
    }

    public function updateAdGroup($id, $data)
    {
        $group = $this->adGroupModel->findById($id,['id']);
        if (!$group){
            return [false,'分组不存在'];
        }
        $r = $this->adGroupModel->updateById($id, $data);
        if ($r){
            return [true,'更新成功'];
        }
        return [false,'没有改变'];
    }

    public function delGroup($ids)
    {
        $groupEx = $this->adGroupModel->getSomeByIds($ids,['id']);
        if ($groupEx->isEmpty()){
            return [false,'分组不存在或已被删除'];
        }
        $r = $this->adGroupModel->delByIds($ids);
        if ($r){
            return [true,'删除成功'];
        }
        return [false,'删除失败'];
    }


    public function allAd($params=[])
    {
        return $this->adModel
            ->getAll($params,['id','group_id','sort','name','show_status','cover','jump_method','jump_url',])
            ->toArray();
    }

    public function addAd($params, $adminId=0)
    {
        $group = $this->adGroupModel->findById($params['group_id'],['id']);
        if (!$group){
            return [false,'图组数据不存在'];
        }
        $lock = TempRedisCode::addAdLock($adminId);
        $this->lockError($lock);
        $r = $this->adModel->addOne($params);
        $this->freeLock($lock);
        if ($r){
            return [true,'添加成功'];
        }
        return [false,'添加失败'];
    }

    public function updateAd($id, $data)
    {
        $ad = $this->adModel->findById($id, ['id']);
        if (!$ad){
            return [false,'数据不存在'];
        }
        $r = $this->adModel->updateById($id, $data);
        if ($r){
            return [true,'更新成功'];
        }
        return [false,'没有改变'];
    }

    public function delAd($ids)
    {
        $ads = $this->adModel->getSomeByIds($ids,['id']);
        if ($ads->isEmpty()){
            return [true,'数据不存在'];
        }
        $r = $this->adModel->delByIds($ids);
        if ($r){
            return [true,'删除成功'];
        }
        return [false,'删除失败'];
    }
}